<?php


namespace app\site\controller;



use app\site\middleware\CheckAuth;
use app\site\middleware\CheckLogin;
use app\site\middleware\OperateLog;

use app\site\service\SiteReqService;
use think\db\exception\DbException;
use think\db\Query;


class AController {

    protected SiteReqService $reqSer;

    /**
     * 登录中间件
     * 权限中间件
     * @var array
     */
    protected array $middleware = [
        CheckLogin::class,
        CheckAuth::class => [
            'only' 	=> ['index', 'add','edit', 'del']
        ],
    ];

    public function __construct()
    {

        $this->reqSer = SiteReqService::instance();
        $this->initialize();
    }

    /**
     * 对象初始化方法
     * @return void
     */
    protected function initialize(){

    }

    protected function param($key='', $default=''){
        $data = request()->param($key, $default);
        if (is_array($data)){
            unset($data['create_time']);
            unset($data['update_time']);
        }
        return $data;
    }

    protected function post($key='', $default=''){
        $data = request()->post($key, $default);
        if (is_array($data)){
            unset($data['create_time']);
            unset($data['update_time']);
        }
        return $data;
    }

    /**
     * @throws DbException
     */
    protected function paginate(Query $query): \think\Paginator
    {
        $limit = $this->param('limit', 20);
        $field = $this->param('field', 'id');
        $order = $this->param('order', 'desc');
        return $query->order("{$field} {$order}")->paginate($limit);
    }

    /**
     * @throws DbException
     */
    protected function jsonPaginate(Query $query): \think\response\Json
    {
        $list = $this->paginate($query);
        return jsonSuccess([
            'items' => $list->items(),
            'total' => $list->total(),
        ]);
    }

    protected function jsonDelete(Query $query): \think\response\Json
    {
        $ids = $this->param('ids');
        $query->where('id', 'in', $ids)->delete();
        return jsonSuccess();
    }
}
